package com.wdhcr.osspolicy.component;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.wdhcr.osspolicy.config.OssProperties;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ description: oss 上传文件组件
 * @ author: wdhcr
 * @ dateTime: 2021/3/7 19:32
 */
@Component
public class OssComponent {


    @Autowired
    private OSSClient ossClient;

    @Autowired
    private OssProperties ossProperties;

    /**
     * 上传文件的前缀、可忽略
     */
    private static final String dir = "";


    public Map<String, String> getPolicy() {

        // host的格式为 bucketname.endpoint
        final String host = "http://" + ossProperties.getBucket() + "." + ossProperties.getEndpoint();
        // 直传有效截止时间
        long expireEndTime = System.currentTimeMillis() + (ossProperties.getExpireTime() * 1000);
        Date expiration = new Date(expireEndTime);
        PolicyConditions policyConditions = new PolicyConditions();
        // 设置可上传文件的大小
        policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, ossProperties.getMin(), ossProperties.getMax());
        // 设置上传文件的前缀、可忽略
        policyConditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
        // 生成policy
        String postPolicy = ossClient.generatePostPolicy(expiration, policyConditions);
        byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        String postSignature = ossClient.calculatePostSignature(postPolicy);
        // 封装policy等信息
        Map<String, String> aliOssPolicy = new HashMap<>();
        aliOssPolicy.put("ossAccessKeyId", ossProperties.getAccessId());
        aliOssPolicy.put("policy", encodedPolicy);
        aliOssPolicy.put("signature", postSignature);
        aliOssPolicy.put("dir", dir);
        aliOssPolicy.put("host", host);
        aliOssPolicy.put("expire", String.valueOf(expireEndTime / 1000));
        aliOssPolicy.put("callback", getCallBackBody());
        return aliOssPolicy;
    }

    /**
     * 获得url链接
     *
     * @ param key
     * @ return
     */
    public String getUrl(String key) {
        if (StringUtils.isBlank(key)) {
            return "";
        }
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        URL url = ossClient.generatePresignedUrl(ossProperties.getBucket(), key, expiration);
        if (url != null) {
            return url.toString().replace("http","https");
        }
        return null;
    }

    /**
     * 验证上传回调的Request
     *
     * @ param request
     * @ return
     * @ throws NumberFormatException
     * @ throws IOException
     */
    public boolean VerifyOSSCallbackRequest(HttpServletRequest request,String ossCallbackBody)
            throws NumberFormatException, IOException {
        boolean ret;
        String autorizationInput = request.getHeader("Authorization");
        String pubKeyInput = request.getHeader("x-oss-pub-key-url");
        byte[] authorization = BinaryUtil.fromBase64String(autorizationInput);
        byte[] pubKey = BinaryUtil.fromBase64String(pubKeyInput);
        String pubKeyAddr = new String(pubKey);
        if (!pubKeyAddr.startsWith("http://gosspublic.alicdn.com/")
                && !pubKeyAddr.startsWith("https://gosspublic.alicdn.com/")) {
            System.out.println("pub key addr must be oss addrss");
            return false;
        }
        String retString = executeGet(pubKeyAddr);
        retString = retString.replace("-----BEGIN PUBLIC KEY-----", "");
        retString = retString.replace("-----END PUBLIC KEY-----", "");
        String queryString = request.getQueryString();
        String uri = request.getRequestURI();
        String authStr = java.net.URLDecoder.decode(uri, "UTF-8");
        if (queryString != null && !queryString.equals("")) {
            authStr += "?" + queryString;
        }
        authStr += "\n" + ossCallbackBody;
        ret = doCheck(authStr, authorization, retString);
        return ret;
    }

    /**
     * 获取Post消息体
     *
     * @ param is
     * @ param contentLen
     * @ return
     */
    public String GetPostBody(InputStream is, int contentLen) {
        if (contentLen > 0) {
            int readLen = 0;
            int readLengthThisTime = 0;
            byte[] message = new byte[contentLen];
            try {
                while (readLen != contentLen) {
                    readLengthThisTime = is.read(message, readLen, contentLen - readLen);
                    if (readLengthThisTime == -1) {// Should not happen.
                        break;
                    }
                    readLen += readLengthThisTime;
                }
                return new String(message);
            } catch (IOException e) {
            }
        }
        return "";
    }

    private String getCallBackBody() {
        Map<String, String> map = new HashMap<>();
        map.put("callbackUrl", ossProperties.getCallbackUrl());
        map.put("callbackBody", "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
        map.put("callbackBodyType", "application/x-www-form-urlencoded");
        String s = JSON.toJSONString(map);
        String base64CallbackBody = null;
        try {
            base64CallbackBody = BinaryUtil.toBase64String(s.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return base64CallbackBody;
    }

    /**
     * 验证RSA
     *
     * @ param content
     * @ param sign
     * @ param publicKey
     * @ return
     */
    private boolean doCheck(String content, byte[] sign, String publicKey) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = BinaryUtil.fromBase64String(publicKey);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
            java.security.Signature signature = java.security.Signature.getInstance("MD5withRSA");
            signature.initVerify(pubKey);
            signature.update(content.getBytes());
            boolean bverify = signature.verify(sign);
            return bverify;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 获取public key
     *
     * @ param url
     * @ return
     */
    @SuppressWarnings({"finally"})
    private String executeGet(String url) {
        BufferedReader in = null;

        String content = null;
        try {
            // 定义HttpClient
            @SuppressWarnings("resource")
            DefaultHttpClient client = new DefaultHttpClient();
            // 实例化HTTP方法
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);

            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            content = sb.toString();
        } catch (Exception e) {
        } finally {
            if (in != null) {
                try {
                    in.close();// 最后要关闭BufferedReader
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return content;
        }
    }
}
